<?php

namespace App\Models;

use App\Models\Traits\DataScopeHelper;
use EloquentFilter\Filterable;
use Illuminate\Http\Exceptions\HttpResponseException;

class ApiBaseModel extends BaseModel
{
    //模型字段过滤器
    use Filterable;
    use DataScopeHelper;

    protected $dateFormat = 'U';

    public static function boot()
    {
        parent::boot();
        //监听模型创建事件
        static::creating(function ($model) {
            if ($model->isFillable('create_by')) {
                if (!$model->create_by) {
                    $model->create_by = auth()->id() ?? -1;
                }
            }
            if ($model->isFillable('update_by')) {
                // $model->update_by = auth()->id() ?? -1;
                if (!$model->update_by) {
                    $model->update_by = auth()->id() ?? -1;
                }
            }
        });
        //监听模型更新之前事件 todo判断数据权限
        static::updating(function ($model) {
            if ($model->isFillable('create_by')) {
                //获取权限范围id
                $scope_info = $model->getCreateByIds();
                if ($scope_info['scope'] == 'limit' && !in_array($model->create_by, $scope_info['ids'])) {
                    throw new HttpResponseException(error('非法操作更新数据'));
                }
                unset($model->attributes['create_by']);
            }
            //获取当前登录用户ID
            if ($model->isFillable('update_by')) {
                $model->update_by = auth()->id() ?? -1;
            }
        });

        //监听模型删除之前事件 todo判断数据权限
        static::deleting(function ($model) {
            if ($model->isFillable('create_by')) {
                //获取权限范围id
                $scope_info = $model->getCreateByIds();
                if ($scope_info['scope'] == 'limit' && !in_array($model->create_by, $scope_info['ids'])) {
                    throw new HttpResponseException(error('非法操作删除数据'));
                }
            }
        });

        //        static::addGlobalScope(new DataFilterScope);
    }


    /**
     * 为 array / JSON 序列化准备日期格式
     *
     * @param  \DateTimeInterface  $date
     * @return string
     */
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    protected function authScope()
    {
    }
}
